<!--vue模板-->
<template>
  <div>
    <div
      class="tip"

    >询价清单以及要求

    </div>
    <el-form ref="addForm"
             :model="forwarderInquiry"
             label-width="auto"
             disabled
             style="
        max-width:1000px;
        margin: auto;
        background-color: #fff;
        padding: 20px;
        border: 1px solid #ccc"

    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="客户姓名:">
            <el-input
              v-model="forwarderInquiry.customer_name"
              placeholder="默认填充，直接创建的可以手动填写"
              style="margin-right: 20px;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="询价编码:">
            <el-input v-model="forwarderInquiry.quote_coding" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="询价日期:">
            <el-date-picker
              v-model="forwarderInquiry.quote_data"
              type="datetime"
              placeholder="请选择日期"
              style="width: 388px;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="货物种类:">
            <el-input v-model="forwarderInquiry.type_goods" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="运输方式:">
            <el-select v-model="forwarderInquiry.transport_way" placeholder="海运/铁路/公路/空运/多联式/散货"
                       style="margin-right: 20px;">
              <el-option
                v-for="item in method"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="航线选择">
            <el-select v-model="forwarderInquiry.route" placeholder="请选择">
              <el-option v-for="item in airline" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="起运港:">
            <el-input v-model="forwarderInquiry.port_of_departure" placeholder="请输入" style="margin-right: 20px;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="目的港:">
            <el-input v-model="forwarderInquiry.port_of_destination" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="报价条款:">
            <el-select v-model="forwarderInquiry.quotation_terms" placeholder="请选择 " style="width: 388px;">
              <el-option
                v-for="item in offerTerms"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="货物描述:">
            <el-input v-model="forwarderInquiry.description_goods" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="HS编码:">
            <el-input v-model="forwarderInquiry.hs_code" placeholder="请输入" style="margin-right: 20px;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="柜型选择:">
            <el-select v-model="forwarderInquiry.cabinet_type" placeholder="请选择 ">
              <el-option v-for="item in cabinetType" :key="item.value" :label="item.label" :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div
      class="tip"
      style="margin-top: 20px;"
    >
      产品信息
    </div>

    <el-table :data="tableData" style="
        max-width:1000px;
        margin: auto;
        background-color: #fff;
        padding: 20px;
        border: 1px solid #ccc">
      <el-table-column prop="product_number" label="产品编号" width="120"/>
      <el-table-column prop="product_name" label="产品名称" width="120"/>
      <el-table-column prop="pieces" label="总件数" width="180"/>
      <el-table-column prop="gross_weight" label="总毛重 (kg)" width="180"/>
      <el-table-column prop="volume" label="总体积 (CBM)" width="180"/>
      <el-table-column prop="support_number" label="总托数" width="180"/>
    </el-table>

    <!--分页-->
    <div
      class="tip"

    >
      <el-pagination
        background
        :page-size="pageSize"
        layout="total,sizes,prev, pager, next,jumper"
        :total="total"
        @size-change="chgsize"
        @current-change="chgpg"
      />
    </div>
    <div class="tip" style="margin-top: 20px;">报价</div>
    <el-form
      label-width="auto"
      :model="forwarderInquiryBao"
      ref="addFormBao"
      style="
        max-width:1000px;
        margin: auto;
        background-color: #fff;
        padding: 20px;
        border: 1px solid #ccc">
      <el-row>
        <el-col :span="12">
          <el-form-item label="报价条款:">
            <el-select v-model="forwarderInquiryBao.terms" placeholder="请选择 " style="width: 344px;">
              <el-option
                v-for="item in offerTerms"
                :key="item.value"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="RMB费用:">
            <el-input v-model="forwarderInquiryBao.rmb" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="海运费USD:">
            <el-input v-model="forwarderInquiryBao.usd" placeholder="请输入" style="width: 344px;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="目的港费用合计:">
            <el-input v-model="forwarderInquiryBao.endport" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="报价有效期:">
            <el-date-picker
              v-model="forwarderInquiryBao.validity_period"
              type="datetime"
              placeholder="请选择日期"
              style="width: 344px;"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="海运费合计:">
            <el-input v-model="forwarderInquiryBao.transportation_total" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="航公司:">
            <el-input v-model="forwarderInquiryBao.shipping_company" placeholder="请输入" style="margin-right: 20px;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="报价时间:">
            <el-date-picker
              v-model="forwarderInquiryBao.create_time"
              type="datetime"
              placeholder="请选择日期"
              style="width: 364px;"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="航次:">
            <el-input v-model="forwarderInquiryBao.voyage" placeholder="请输入" style="width: 344px;"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="航程:">
            <el-input v-model="forwarderInquiryBao.voyage_distance" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>
<!--      :on-success="handleUploadSuccess"
      :on-error="handleUploadError"
      :limit="1"
      :file-list="fileList"
      :before-upload="beforeUpload"-->
      <el-row>
        <el-col :span="12">
          <el-form-item label="上传截图:" class="icon">
            <el-upload
              class="avatar-uploader"
              :action="host + '/upload'"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload"
              :on-success="handleAvatarSuccess"
            >   <!--limit=1 限制上传文件个数为1-->

              <el-button
                type="default"
              >
                <el-icon>
                  <upload/>
                </el-icon>
                上传文件
              </el-button>
              <template #tip>
                <div class="el-upload__tip">支持扩展名：.png .jpg ...</div>
              </template>
            </el-upload>
            <el-button
              v-if="imageUrl"
              type="danger"
              @click="removeImage"
              style="margin-top: -41px"
            >
              删除截图
            </el-button>
          </el-form-item>

        </el-col>
      </el-row>
    </el-form>

    <div style="text-align: center; margin: 20px">
      <el-button type="primary" @click="save">保存</el-button>
      <el-button type="info" @click="close">取消</el-button>
    </div>

  </div>

</template>

<!--vue 组件选项定义-->
<script setup>
import {ref, onBeforeMount, onMounted} from "vue";
import {useRouter, useRoute} from "vue-router";
import {ElMessage} from "element-plus";
//引入api
import {
  getForwarderInquiryById,
  saveForwarderInquiry,
} from "@/api/forwarderInquiry.js";
import host from "@/utils/env.js";
import {saveForwarderQuote} from "@/api/forwarderQuote.js";
//路由实例
const router = useRouter();
const route = useRoute();
const imageUrl = ref("");
const isImageUploaded = ref(false)

const method = [
  {
    label: "海运",
    value: 1
  },
  {
    label: "铁路",
    value: 2
  },
  {
    label: "公路",
    value: 3
  }, {
    label: "空运",
    value: 4
  },
  {
    label: "多联式",
    value: 5
  },
  {
    label: "散货",
    value: 6
  }
];
const airline = [
  {
    label: "中国-北美",
    value: 1
  },
  {
    label: "中国-美加",
    value: 2
  },
  {
    label: "中国-欧洲",
    value: 3
  },
  {
    label: "中国-澳大利亚/新西兰",
    value: 4
  },
  {
    label: "中国-中南美",
    value: 5
  },
  {
    label: "中国-红海/地中海",
    value: 6
  },
  {
    label: "中国-日本/韩国/俄罗斯",
    value: 7
  },
  {
    label: "中国-东南亚",
    value: 8
  },
  {
    label: "中国-中东/波斯湾",
    value: 9
  },
  {
    label: "中国-中东/印巴",
    value: 10
  },
  {
    label: "中国-黑海/亚德里海湾",
    value: 11
  },
  {
    label: "中国-南美东/南美西",
    value: 12
  },
  {
    label: "中国-欧洲内陆",
    value: 13
  },
  {
    label: "中国-东非",
    value: 14
  },
  {
    label: "中国-西非",
    value: 15
  },
  {
    label: "中国-南非",
    value: 16
  },
  {
    label: "中国-北非",
    value: 17
  },
  {
    label: "中国-加勒比海",
    value: 18
  },
  {
    label: "中国-大马士革",
    value: 19
  },
  {
    label: "中国-科隆",
    value: 20
  },
  {
    label: "中国-菲律宾",
    value: 21
  },
  {
    label: "中国-香港/澳门",
    value: 22
  }
];
//报价条款
const offerTerms = [
  {
    label: "CFR",
    value: 1
  },
  {
    label: "CIF",
    value: 2
  },
  {
    label: "DDU",
    value: 3
  },
  {
    label: "DAP",
    value: 4
  },
  {
    label: "DDP",
    value: 5
  },
  {
    label: "其他",
    value: 6
  }
];
//柜型选择
const cabinetType = [
  {
    label: "拼箱",
    value: 1
  },
  {
    label: "20GP",
    value: 2
  },
  {
    label: "40GP",
    value: 3
  },
  {
    label: "20HQ",
    value: 4
  },
  {
    label: "40HQ",
    value: 5
  },
  {
    label: "20FR",
    value: 6
  }
  ,
  {
    label: "40FR",
    value: 7
  }
  ,
  {
    label: "200T",
    value: 8
  },
  {
    label: "400P",
    value: 9
  }
  ,
  {
    label: "散货",
    value: 10
  }
]
//分页信息
const page = ref(1); //当前页 默认第1页
const pageSize = ref(10); //每页记录数
const total = ref(0); //总记录数
//表格数据
const tableData = ref([]);

//每页记录数变化
function chgsize(size) {
  //更改每页记录数
  pageSize.value = size;
  //从每页开始查询
  page.value = 1;
  //查询数据
  initData();
}

//页面发生变化
function chgpg(pg) {
  //更改当前页
  page.value = pg;
  //查询数据
  initData();
}


//表单引用  声明同名引用
const addForm = ref();
const addFormBao = ref();
//第二个表单对象
const forwarderInquiryBao = ref({
  terms: "",
  rmb: null,
  usd: null,
  endport: null,
  validity_period: "",
  transportation_total: "",
  shipping_company: "",
  voyage: "",
  voyage_distance: null,
  screenshot: "",
  create_time: "",
  inquiry: "",
  status:null,
})

//表单对象
const forwarderInquiry = ref({
  customer_id: "",
  customer_name: "",
  quote_coding: "",
  quote_data: "",
  type_goods: "",
  transport_way: "",
  route: "",
  port_of_departure: "上海",
  port_of_destination: "",
  quotation_terms: "",
  description_goods: "",
  hs_code: "84749000",
  cabinet_type: "",
  /* product_number: "",
   product_name: "",
   pieces: "",
   gross_weight: "",
   volume: "",
   support_number: "",*/
  products: [] // 产品信息列表
});


//取消
function close() {
  router.push("/forwarder/price");
}

//上传前
const beforeAvatarUpload = rawFile => {
  if (isImageUploaded.value) {
    ElMessage.error("已经存在一张截图，请删除后再上传");
    return false;
  }
  if (rawFile.type !== "image/jpeg") {
    ElMessage.error("请选择jpg格式");
    return false;
  } else if (rawFile.size / 1024 / 1024 > 10) {
    ElMessage.error("图片不能超过10M!");
    return false;
  }
  return true;
};

//上传成功
const handleAvatarSuccess = (response, uploadFile) => {
  if (response.code == 200) {
    ElMessage.success("上传成功");
    //显示图片
    imageUrl.value = URL.createObjectURL(uploadFile.raw);

    //更改图片地址
    forwarderInquiryBao.value.screenshot = imageUrl.value;
    console.log(forwarderInquiryBao.value.screenshot)
    isImageUploaded.value = true; // 将布尔值设置为true，表示图片已经上传
  }
};

// 删除图片
const removeImage = () => {
  imageUrl.value = "";
  forwarderInquiryBao.value.screenshot = "";
  isImageUploaded.value = false;
  ElMessage.info("截图已删除");
};

//保存&编辑
async function save() {
  //发请求前将把这些字段的值转换为数值类型
  forwarderInquiryBao.value.rmb = parseFloat(forwarderInquiryBao.value.rmb);
  forwarderInquiryBao.value.usd = parseFloat(forwarderInquiryBao.value.usd);
  forwarderInquiryBao.value.endport = parseFloat(forwarderInquiryBao.value.endport);
  forwarderInquiryBao.value.voyage_distance = parseFloat(forwarderInquiryBao.value.voyage_distance);


  forwarderInquiryBao.value.inquiry = route.query.quote_coding; // 报价单号
  // 将 value 替换为 label
  forwarderInquiry.value.transport_way = method.find(item => item.value === forwarderInquiry.value.transport_way)?.label;
  forwarderInquiry.value.route = airline.find(item => item.value === forwarderInquiry.value.route)?.label;
  forwarderInquiry.value.quotation_terms = offerTerms.find(item => item.value === forwarderInquiry.value.quotation_terms)?.label;
  forwarderInquiry.value.cabinet_type = cabinetType.find(item => item.value === forwarderInquiry.value.cabinet_type)?.label;
  forwarderInquiryBao.value.terms = offerTerms.find(item => item.value === forwarderInquiryBao.value.terms)?.label;

  forwarderInquiryBao.value.status = 2; // 报价状态 2 已报价

    //如果是添加模式，调用保存Api
    let res = await saveForwarderQuote(forwarderInquiryBao.value);
   console.log("请求的数据", forwarderInquiryBao.value)
    if (res.code === 200) {
      ElMessage({
        message: "保存成功",
        type: "success"
      });

      close();
    }

}

/**
 * 根据询价编码加载询价单数据和产品信息
 * @param quote_coding 询价编号
 * @returns
 */
async function initData() {
  //从报价页面拿到的询价编号
  const  quote_coding = route.query.quote_coding;
  //请求
  let data = {
    page: page.value,
    pageSize: pageSize.value,
  };
  let res = await getForwarderInquiryById(quote_coding,data.page,data.pageSize);
  console.log("修改拿到的数据", res)
  if (res.code === 200) {
    forwarderInquiry.value = res.data.data[0];

    // 将 label 映射回 value
    forwarderInquiry.value.transport_way = method.find(item => item.label === forwarderInquiry.value.transport_way)?.value;
    forwarderInquiry.value.route = airline.find(item => item.label === forwarderInquiry.value.route)?.value;
    forwarderInquiry.value.quotation_terms = offerTerms.find(item => item.label === forwarderInquiry.value.quotation_terms)?.value;
    forwarderInquiry.value.cabinet_type = cabinetType.find(item => item.label === forwarderInquiry.value.cabinet_type)?.value;

    // 确保 tableData.value 是一个数组
    tableData.value = forwarderInquiry.value.products || [];
    //接收分页信息
    page.value = res.data.page;
    pageSize.value = res.data.pageSize;
    total.value = res.data.total;
  }

}


// 在 script setup 部分添加格式化日期的函数
function formatDate(date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要+1
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  const seconds = String(date.getSeconds()).padStart(2, '0');
  return `${year}-${month}-${day}T${hours}:${minutes}:${seconds}`;
}

//生命周期
onBeforeMount(() => {
  //自动加载对应询价单里的询价日期需要赋值
  const currentDate = new Date();
  forwarderInquiryBao.value.create_time = formatDate(currentDate); // 自动填充报价时间
  //forwarderInquiry.value.quote_data = formatDate(currentDate); // 自动填充询价日期,(询价日期是查出来的不用填充)
  // 计算有效期（当前时间 + 5天）
  const validityDate = new Date();
  validityDate.setDate(validityDate.getDate() + 5);
  forwarderInquiryBao.value.validity_period = formatDate(validityDate); // 格式化有效期 // 自动填充报价有效期,当前时间往后加5天
  initData();
});
</script>

<!--vue样式 scoped当前样式只适用于当前组件-->
<style scoped>
.ipt {
  width: 300px;
}

.tip {
  width: 1000px;
  margin: auto;
  height: 60px;
  line-height: 60px;
  border: #ccc solid 1px;
  padding-left: 40px;
}

.icon {
  z-index: 999;
}
</style>

